package com.xxwy.map;

import com.xxwy.link.LinkedList;

/**
 * @author xxwy
 */
public class LinkedListMap<K, V> implements Map<K, V> {

    private class Node {
        private Node next;
        private K key;
        private V value;

        public Node(K key, V value, Node next) {
            this.next = next;
            this.key = key;
            this.value = value;
        }

        public Node(K key) {
            this(key, null, null);
        }

        public Node() {
            this(null, null, null);
        }

        @Override
        public String toString() {
            return key.toString() + " : " + value.toString();
        }
    }

    /**
     * 虚拟头指针
     */
    private Node dummyHead;
    private int size;

    public LinkedListMap() {
        dummyHead = new Node();
    }

    /**
     * 传入key的值，返回这个Key值的结点
     * @param key
     */
    private Node getNode(K key){
        Node cur = dummyHead.next;
        while (cur!=null){
            if(cur.key.equals(key)){
                return cur.next;
            }else {
                cur = cur.next;
            }
        }
        return null;
    }

    @Override
    public void add(K key, V value) {
        //如果key 相同，就更新value
        Node node = getNode(key);
        if (node == null) {
            dummyHead.next = new Node(key,value,dummyHead);
            size++;
        }else {
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {
        Node pre = dummyHead;
        while (pre.next!=null){
            if(pre.next.key.equals(key)){
                break;
            }else {
                pre = pre.next;
            }
        }
        if(pre.next!=null){
            Node delNode = pre.next;
            pre.next=pre.next.next;
            size--;
            delNode.next = null;
            return delNode.value;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        if (node != null) {
            return node.value;
        }
        return null;
    }

    @Override
    public void set(K key, V value) {
        Node node = getNode(key);
        if (node != null) {
            node.value = value;
        }else {
            throw new IllegalArgumentException(key + "is doesn't exist");
        }
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }
}
